package org.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.R;
import org.example.common.StatusCode;
import org.example.pojo.entity.Posts;
import org.example.pojo.vo.PostVo;
import org.example.pojo.vo.FileVo;
import org.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@Api(value = "/api/post", tags = {"}"})
@RestController
@RequestMapping("/api/post")
@Slf4j
public class PostController {
    @Value("${file.upload.path}")
    private String uploadPath;
    @Value("${server.port}")
    private String code;
    @Autowired
    private PostService postService;
    @Autowired
    private HttpServletRequest request;



    /**
     * 分页获取帖子信息数据列表
     *
     * @param page
     * @param size
     * @param title
     * @param delFlag
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "page", value = ""),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "size", value = ""),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "title", value = ""),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "status", value = "")
    })
    @ApiOperation(value = "分页获取帖子信息数据", notes = "分页获取帖子信息数据", httpMethod = "GET")
    @GetMapping("/list/{page}/{size}")
    public R getUserList(@PathVariable(required = false) Integer page,
                         @PathVariable(required = false) Integer size,
                         @RequestParam(required = false) String title,
                         @RequestParam(required = false) String delFlag
    ) {
        log.info("getUserList"+page+size+title+delFlag);
        //分页查询
        Page<PostVo> postPage = postService.pageList(page, size, title, delFlag);

        return R.ok(postPage);
    }
    /**
     * 获取帖子信息
     *
     * @param postId
     * @return
     */
    @GetMapping("/detail/{postId}")
    public R getDetail(@PathVariable String postId) {
        return postService.getPostDetail(postId);
    }

    /**
     * 添加帖子
     *
     * @param post
     * @return
     */
    @ApiOperation(value = "添加帖子", notes = "添加帖子信息", httpMethod = "POST")
    @PostMapping("/add")
    public R addAttr(@RequestBody Posts post) {
        return postService.addPost(post);

    }
    /**
     * 修改帖子
     *
     * @param post
     * @return
     */
    @ApiOperation(value = "修改帖子", notes = "修改帖子信息", httpMethod = "PUT")
    @PutMapping("/update")
    public R updateAttr(@RequestBody Posts post) {
        log.info("updateAttr======="+post);
        return postService.updatePost(post);

    }
    /**
     * 批量删除帖子
     *
     */
    @DeleteMapping("/batch")
    public R deleteBatch(@RequestBody String[] ids) {
        log.info("deleteBatch======="+Arrays.toString(ids));
        postService.removeBatchByIds(Arrays.asList(ids));
        return R.ok("删除成功");
    }
    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "id", value = "", required = true)
    })
    @ApiOperation(value = "删除帖子", notes = "删除帖子", httpMethod = "DELETE")
    @DeleteMapping("/remove/{id}")
    public R removeAttr(@PathVariable String id) {
        postService.removePostById(id);
        return R.ok("操作成功");
    }
    /**
     * 图片上传
     *
     * @param
     * @return
     */
    @ApiOperation(value = "图片上传", notes = "图片上传", httpMethod = "POST")
    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件的原始名称
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return R.error(StatusCode.FILE_UPLOAD_ERROR);
            }

            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("文件后缀：" + suffix);
            // 为文件生成一个唯一的文件名
            String fileName = UUID.randomUUID().toString() + suffix;

            // 获取文件上传路径
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 将文件保存到指定路径
            File destFile = new File(uploadPath + fileName);
            file.transferTo(destFile);
            FileVo fileVo = new FileVo();
            String serverPath = request.getScheme() + "://" + request.getServerName() + ":" + code;
            log.info("serverPath:"+serverPath);
            fileVo.setUrl(serverPath + "/uploads/" + fileName);
            if(suffix.contains("jpg")||suffix.contains("png")||suffix.contains("jpeg")){
                fileVo.setType("1");
            }else if(suffix.contains("mp4")){
                fileVo.setType("2");
            }else {
                return R.error(StatusCode.FILE_TYPE_ERROR);
            }

            // 返回文件的访问路径
            return R.ok(fileVo);
        } catch (IOException e) {
            log.error("文件上传失败", e);

            return R.error(StatusCode.FILE_UPLOAD_ERROR);
        }
    }



}
